package com.mdd.admin.service.index.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdd.admin.service.index.IIndexVisitService;
import com.mdd.admin.validate.common.PageParam;
import com.mdd.admin.validate.index.IndexVisitParam;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.IndexVisit;
import com.mdd.common.entity.course.Course;
import com.mdd.common.mapper.IndexVisitMapper;
import com.mdd.common.utils.TimeUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.*;

/**
 * 首页浏览记录实现类
 * @author panweiliang
 */
@Service
public class IndexVisitServiceImpl implements IIndexVisitService {
        
    @Resource
    IndexVisitMapper indexVisitMapper;

    /**
     * 首页浏览记录新增
     *
     * @author panweiliang
     * @param terminal 参数
     * @param ip
     */
    @Override
    public void addOrUpdate(Integer terminal, String ip) {
        IndexVisit indexVisit = indexVisitMapper.selectOne(
                new QueryWrapper<IndexVisit>()
                        .eq("ip", ip)
                        .eq("terminal", terminal)
                        .ge("update_time",TimeUtil.today().get(0))
                        .le("update_time", TimeUtil.today().get(1))
                        .isNull("delete_time")
                        .last("limit 1"));

        if (indexVisit != null) {
            indexVisit.setVisit(indexVisit.getVisit() + 1);
            indexVisit.setUpdateTime(TimeUtil.timestamp());
            indexVisitMapper.updateById(indexVisit);
        } else {
            IndexVisit model = new IndexVisit();
            model.setIp(ip);
            model.setTerminal(terminal);
            model.setVisit(1);
            model.setCreateTime(System.currentTimeMillis() / 1000);
            model.setUpdateTime(System.currentTimeMillis() / 1000);
            indexVisitMapper.insert(model);
        }
    }

    /**
     * 获取总的用户总访问量
     *
     * @author panweiliang
     */
    public Long getTotalVisitCount() {
        return this.indexVisitMapper.getTotalVisitCount();
    }

    @Override
    public Long getVisitCount(Long start, Long end) {
        return this.indexVisitMapper.getVisitCount(start, end);
    }

    @Override
    public Long getTotalUserVisitCount() {
        return this.indexVisitMapper.getTotalUserVisitCount();
    }

    @Override
    public Long getUserVisitCount(Long start, Long end) {
        return this.indexVisitMapper.getTotalVisitCountByTimestamp(start, end);
    }
}
